import { createContext, useCallback, useRef, useState, useContext } from 'react'

const useDialog = () => {
  const [scrollOffset, setScrollOffset] = useState(0)
  const scrollRef = useRef(null)

  const scrollTo = useCallback(({ y }) => {
    if (!scrollRef.current) return

    if (scrollRef.current.scrollTo) {
      scrollRef.current.scrollTo({ y, animated: false })
    } else if (scrollRef.current.scrollToOffset) {
      scrollRef.current.scrollToOffset({ offset: y, animated: false })
    }
    scrollRef.current.flashScrollIndicators?.()
  }, [])
  const onScroll = useCallback((e) => {
    setScrollOffset(e.nativeEvent.contentOffset.y)
  }, [])

  return {
    scrollOffset,
    scrollTo,
    scrollRef,
    onScroll,
  }
}

export const DialogContext = createContext()

export const useDialogContext = () => {
  return useContext(DialogContext)
}

export default useDialog
